<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<CustomNavBar 
			:show-back="true" 
			:show-logo="false" 
			title="仓库管理"
			background-color="#ffffff"
			@back="handleBack"
			ref="navBarRef"
		/>
		
		<view class="content-wrapper" :style="{ paddingTop: navHeight + 'px' }">
			<!-- #ifdef APP-PLUS -->
		 <view v-if="decodedLink" class="empty">
				<text>正在打开页面...</text>
			</view>
			<view v-else class="empty">
				<text>无效的链接</text>
			</view>
			<!-- #endif -->

			<!-- #ifndef APP-PLUS -->
		<web-view 
				class="webview-embed" 
				:src="decodedLink" 
				v-if="decodedLink"
				@message="handleWebviewMessage"
			/>
			<view v-else class="empty">
				<text>无效的链接</text>
			</view> 
			<!-- #endif -->
		</view>
    		<!-- 右侧抽屉 -->
		<RightDrawer />
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad, onReady, onUnload, onBackPress } from '@dcloudio/uni-app'
import CustomNavBar from '@/components/CustomNavBar.vue'


const decodedLink = ref('')
const navHeight = ref(0)
const navBarRef = ref(null)

// 仅在 APP 端使用原生子 webview 内嵌页面
let childWebview = null
let canGoBack = false
let isHandlingBack = false // 防止重复触发

onLoad((query) => {
  // 解析仓库链接地址
	if (query && query.link) {
		try {
			decodedLink.value = decodeURIComponent(query.link)
		} catch (e) {
			decodedLink.value = query.link
		}
	}
})

onMounted(() => {
	// 获取导航栏高度
	setTimeout(() => {
		if (navBarRef.value) {
			navHeight.value = navBarRef.value.totalNavHeight
		} else {
			// 如果没有获取到，使用默认值
			const systemInfo = uni.getSystemInfoSync()
			const statusBarHeight = systemInfo.statusBarHeight || 0
			const navBarHeight = 44
			navHeight.value = statusBarHeight + navBarHeight
		}
	}, 50)
})

onReady(() => {
  // #ifdef APP-PLUS
  if (!decodedLink.value) return
// 获取当前页面 WebView 实例
  const pages = getCurrentPages()
  const currentWebview = pages[pages.length - 1].$getAppWebview()
  // 计算子webview的位置和大小 占据除了顶部导航栏外的剩余屏幕
  const statusBarHeight = navBarRef.value?.statusBarHeight || plus.navigator.getStatusbarHeight()
  const titleBarHeight  = navBarRef.value?.navBarHeight || 44
  const topOffset       = statusBarHeight + titleBarHeight

  const screenHeight = plus.screen.resolutionHeight
  const webviewHeight = screenHeight - topOffset

  childWebview = plus.webview.create(decodedLink.value, 'warehouseH5', {
    top:    topOffset + 'px',
    height: webviewHeight + 'px',
    left:   '0px',
    right:  '0px',
    bounce: 'vertical'
  })

  currentWebview.append(childWebview)

  // 监听H5页面加载完成
  childWebview.addEventListener('loaded', () => {
    console.log('H5页面加载完成')
    checkCanGoBack()
  })

  // 监听页面变化
  childWebview.addEventListener('loading', () => {
    setTimeout(checkCanGoBack, 500)
  })
  // #endif
})

// 检查 H5 是否可以返回（返回 Promise）
const checkCanGoBack = () => {
  return new Promise((resolve) => {
    // #ifdef APP-PLUS
    if (!childWebview) {
      resolve(false)
      return
    }

    childWebview.evalJS(`
      (function() {
        try {
          return window.history.length > 1;
        } catch (e) {
          return false;
        }
      })()
    `, (result) => {
      const canBack = Boolean(result)
      console.log('[H5] 是否可返回:', canBack)
      resolve(canBack)
    })
    // #endif

    // #ifndef APP-PLUS
    resolve(false) // web-view 由 H5 自己控制
    // #endif
  })
}


async function handleBack() {
  console.log('CustomNavBar返回按钮被点击')

  if (isHandlingBack) {
    console.log('返回操作已在处理中，跳过')
    return
  }

  isHandlingBack = true

  const timeoutId = setTimeout(() => {
    console.log('返回操作超时，强制释放锁')
    isHandlingBack = false
  }, 1000)

  try {
    // #ifdef APP-PLUS
    if (childWebview) {
      // 使用 plus 提供的 canBack 接口（比 JS 更准确）
      childWebview.canBack((result) => {
		  console.log(result)
        if (result.canBack) {
          console.log('执行原生 childWebview.back()')
          childWebview.back()
          // 成功后释放锁
          setTimeout(() => {
            isHandlingBack = false
            clearTimeout(timeoutId)
          }, 300)
        } else {
			uni.reLaunch({
						url: '/pages/tabs/index'
					})
        }
      })
    } else {
      console.log('childWebview 未创建，执行路由返回')
      uni.navigateBack({
        delta: 1,
        success: () => {
          clearTimeout(timeoutId)
          isHandlingBack = false
        },
        fail: () => {
          uni.redirectTo({ url: '/pages/tabs/index' })
          clearTimeout(timeoutId)
          isHandlingBack = false
        }
      })
    }
    // #endif

    // #ifndef APP-PLUS
    console.log('非 APP 端，执行 uni.navigateBack')
    uni.navigateBack({
      delta: 1,
      success: () => {
        clearTimeout(timeoutId)
        isHandlingBack = false
      },
      fail: () => {
        uni.redirectTo({ url: '/pages/tabs/index' })
        clearTimeout(timeoutId)
        isHandlingBack = false
      }
    })
    // #endif

  } catch (error) {
    console.error('返回操作异常:', error)
    clearTimeout(timeoutId)
    isHandlingBack = false
  }
}

// 处理物理返回键和滑屏手势 - 直接APP路由回退
// // #ifdef APP-PLUS
// let lastBackTime = 0
// onBackPress((e) => {
//   const now = Date.now()
  
//   // 防止重复触发：500ms内只允许一次返回操作
//   if (now - lastBackTime < 500) {
//     console.log('返回操作防抖，跳过重复触发')
//     return true
//   }
//   lastBackTime = now

//   console.log('物理返回键被触发', e)
  
//   // 确保不是来自顶部按钮的触发
//   if (!isHandlingBack) {
//     console.log('执行APP路由直接返回')
//    uni.reLaunch({
// 			url: '/pages/tabs/index'
// 		})
//   }
//   return true // 阻止默认返回行为，由我们自己处理
// })
// // #endif
// #ifdef APP-PLUS
let lastBackTime = 0
onBackPress(async (e) => {
  const now = Date.now()
  if (now - lastBackTime < 500) {
    console.log('防抖：忽略重复返回')
    return true
  }
  lastBackTime = now

  await handleBack()
  return true // 阻止默认行为
})
// #endif

// 处理web-view消息 - 简化处理
const handleWebviewMessage = (e) => {
  console.log('收到web-view消息:', e);
  // 这里可以处理H5页面发送的其他消息
}

// 清理监听器
onUnload(() => {
	// #ifdef APP-PLUS
	if (childWebview) {
		try { childWebview.close() } catch (e) {}
		childWebview = null
	}
	// #endif
})
</script>

<style scoped lang="scss">
.container {
	width: 100%;
	height: 100vh;
	background: #fff;
	position: relative;
}

.content-wrapper {
	width: 100%;
	height: 100%;
	position: relative;
}

.webview-embed {
	position: absolute;
	left: 0;
	right: 0;
	width: 100%;
	height: 100%;
}

.empty {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	color: #666;
}
</style>
